package cn.john.org.service.impl;

import cn.john.basic.service.impl.BaseServiceImpl;
import cn.john.basic.util.MD5Utils;
import cn.john.basic.util.PageList;
import cn.john.basic.util.StrUtils;
import cn.john.org.domain.Employee;
import cn.john.org.mapper.EmployeeMapper;
import cn.john.org.query.EmployeeQuery;
import cn.john.org.service.IEmployeeService;
import cn.john.user.domain.LoginInfo;
import cn.john.user.mapper.LoginInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
/* 1. extends BaseServiceImpl<Employee> : 实现基础接口中的方法 */
/* 2. 实现扩展接口 */
@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    /**
     * 注册添加用户
     * @param employee
     */
    @Override
    public void add(Employee employee) {
        // 初始化employee字段
        initEmployee(employee);
        LoginInfo info = new LoginInfo();
        BeanUtils.copyProperties(employee, info);
        // 设置成后端用户
        info.setType(0);
        // 返回自增id
        loginInfoMapper.save(info);
        employee.setLogininfo_id(info.getId());
        employeeMapper.save(employee);
    }

    /**
     * Java 的引用传递
     * 初始化employee字段
     * @param employee
     */
    private void initEmployee(Employee employee) {
        // 只有初始化盐值和密码
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(employee.getPassword() + salt);
        employee.setSalt(salt);
        employee.setPassword(md5Pwd);
    }


    /**
     * 删除员工
     * @param id
     */
    @Override
    public void remove(Long id) {
        // 查询出员工，拿到logininfo_id
        Employee employee = employeeMapper.loadById(id);
        // 先删除loginInfo
        loginInfoMapper.delete(employee.getLogininfo_id());
        // 再删除员工employee
        employeeMapper.delete(id);
    }
}
